export function loadMap() {
  if (window.BMapGL && window.BMapGL.Map) {
    return Promise.resolve()
  }

  let script = document.createElement('script')
  script.type = 'text/javascript'
  script.async = true
  script.src = `https://api.map.baidu.com/api?v=1.0&type=webgl&ak=${process.env.VUE_APP_BAIDU_AK}&callback=__initializeMap`

  let promise = new Promise((resolve, reject) => {
    window.__initializeMap = () => {
      return resolve()
    }

    script.onerror = (error) => {
      return reject(error)
    }
  })

  document.head.appendChild(script)

  return promise
}

export function reverseGeoCode(point) {
  let script = document.createElement('script')
  let location = point.lat + ',' + point.lng
  script.type = 'text/javascript'
  script.async = true
  script.src = `https://api.map.baidu.com/reverse_geocoding/v3/?ak=${process.env.VUE_APP_BAIDU_AK}&output=json&coordtype=bd09ll&location=${location}&callback=__handleGeoCode`

  let promise = new Promise((resolve, reject) => {
    window.__handleGeoCode = (res) => {
      if (res.status) return reject(res)
      else return resolve(res.result)
    }

    script.onerror = (error) => {
      return reject(error)
    }
  })

  document.head.appendChild(script)

  return promise
}
